package cn.ybk.aop;

import cn.ybk.org.domain.Department;
import cn.ybk.system.domain.Aop;
import cn.ybk.system.service.AopService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class LogAop {

    @Autowired
    private AopService aopService;

    @Pointcut("@annotation(cn.ybk.aop.Anno)")
    public void aop(){
    }

    // 需要获取访问ip 方法名称（获取到了） 时间 描述中：想办法区分是添加还是修改
    @Around("aop()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {

        Aop aop = new Aop();

        long l = System.currentTimeMillis();
        log.info("时间毫秒数:{}",l);

        // 获取方法名
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        String name = method.getName();
        log.info("方法名称为:{}",name);


        // 获取访问ip
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getRemoteHost();
//        String url = request.getRequestURL().toString();
        log.info("请求源IP:{}",ip);


//        // 获取访问方法是添加或者修改
        Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
        Anno annotation = method.getAnnotation(Anno.class);
        String des = annotation.des();
        Object[] args = pjp.getArgs();
//        log.info("参数:{}",args);

        Department Department = (Department) args[0];
        Long id = Department.getId();

        des = id == null ? "添加方法":"修改方法";
        log.info("方法描述des:{}",des);

        // 获取时间毫秒数
        long l1 = System.currentTimeMillis();
        long date = l1 - l;
        log.info("{}毫秒",date);

        aop.setIp(ip);
        aop.setDate(date);
        aop.setDes(des);
        aop.setMethods(name);

        aopService.add(aop);

        Object proceed = pjp.proceed();
        return proceed;
    }
}
